<script setup lang="ts">
import { reactive, ref } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, Col, Form, FormItem, Input, message, Popconfirm, Row, Select, Switch, Table } from 'ant-design-vue'

import { confirmSelect, del_purchase_bind_api, get_purchase_info_api, getInsertPurchaseBomFormApi, getPurchaser, notsplitOrder } from '#/api/spuBom'

import SplitList from './SplitList.vue'

const emit = defineEmits(['refresh'])

// 定义组件props并获取props引用
const PurchaseList = ref([])
const NeedPurchaseList = ref([])
const Options = ref([])
const loading = ref(false)
const handleSupplySearch = useDebounceFn(async (keyword) => {
  loading.value = true
  try {
    const res = await getPurchaser({
      quick_search: keyword || '',
      page: 1,
      limit: 10,
      initKey: 'id',
      select: true,
    })

    Options.value = res.data.data.list.map((it: any) => ({ label: it.realname, value: it.id }))
  } finally {
    loading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleSupplyDropdown = (open: any) => {
  if (open && Options.value.length === 0) {
    handleSupplySearch('')
  }
}

const formModel = reactive({
  search_text: '',
  purchase_user: '',
  show_bind: false,
  is_material: false,
})

const columns: any = [
  { title: '采购单号', dataIndex: 'caigou_id', key: 'caigou_id', align: 'center' },
  { title: '手工单号', dataIndex: 'purchase_sn', key: 'purchase_sn', align: 'center' },
  { title: '采购日期', dataIndex: 'purchase_time', key: 'purchase_time', align: 'center' },
  { title: '交期', dataIndex: 'dead_line', key: 'dead_line', align: 'center' },
  { title: '物料名称', dataIndex: 'res', key: 'res', align: 'center' },
  { title: '采购单价', dataIndex: 'price', key: 'price', align: 'center' },
  { title: '下单数量', dataIndex: 'purchase_num', key: 'purchase_num', align: 'center' },
  { title: '实际收料数量', dataIndex: 'reviced_num', key: 'reviced_num', align: 'center' },
  { title: '累计退料数量', dataIndex: 'refund_num', key: 'refund_num', align: 'center' },
  { title: '未发/库存数量', dataIndex: 'stock_num', key: 'stock_num', align: 'center' },
  { title: '操作', dataIndex: 'action', key: '', align: 'center' },
]

const columns1: any = [
  { title: '采购员', dataIndex: 'realname', key: 'realname', align: 'center' },
  { title: '采购单号', dataIndex: 'caigou_id', key: 'caigou_id', align: 'center' },
  { title: '手工单号', dataIndex: 'purchase_sn', key: 'purchase_sn', align: 'center' },
  { title: '采购日期', dataIndex: 'purchase_time', key: 'purchase_time', align: 'center' },
  { title: '交期', dataIndex: 'dead_line', key: 'dead_line', align: 'center' },
  { title: '面料名称', dataIndex: 'scope', key: 'scope', align: 'center' },
  { title: '采购单价', dataIndex: 'price', key: 'price', align: 'center' },
  { title: '供应商', dataIndex: 'SupplyNa', key: 'SupplyNa', align: 'center' },
  { title: '下单数量', dataIndex: 'purchase_num', key: 'purchase_num', align: 'center' },
  { title: '实手数量', dataIndex: 'reviced_num', key: 'reviced_num', align: 'center' },
  { title: '可拆/库存数量', dataIndex: 'stock_num', key: 'stock_num', align: 'center' },
  { title: '被绑定信息', dataIndex: 'be_text', key: 'be_text', align: 'center' },
  { title: '操作', dataIndex: 'action', key: '', align: 'center' },
]

function initDataPurchaseList(id: any) {
  const param = {
    bom_detail_id: id,
  }
  get_purchase_info_api(param).then((response) => {
    PurchaseList.value = response.data.data
  })
}
function initadataNeedPurchaseList() {
  const param = {
    bom_detail_id: id.value,
    need_num: need_num.value,
    material_sku_id: sku_id.value,
    ...formModel,
  }
  getInsertPurchaseBomFormApi(param).then((response) => {
    NeedPurchaseList.value = response.data.data
  })
}

const id = ref('')
const need_num = ref('')
const sku_id = ref('')

const [Modal, modalApi] = useVbenModal({
  appendToMain: true,
  class: 'w-2/3',
  showConfirmButton: false,
  onCancel() {
    modalApi.close()
  },
  async onConfirm() {},
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return
    const { data } = modalApi.getData<Record<string, any>>()
    id.value = data.id
    need_num.value = data.need_num
    sku_id.value = data.sku_id
    initDataPurchaseList(data.id)
    initadataNeedPurchaseList()
  },
})

// 新增绑定
function addBut(row: any) {
  const param = {
    purchase_bom_detail_id: row.purchase_bom_detail_id,
    bom_detail_id: id.value,
  }
  confirmSelect(param).then((res) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
    } else {
      message.error(res.data.msg)
    }
    initDataPurchaseList(id.value)
    initadataNeedPurchaseList()
  })
  emit('refresh')
}
// 解除绑定
// 新增绑定
function delBut(row: any) {
  const param = {
    purchase_bom_detail_id: row.purchase_bom_detail_id,
  }
  del_purchase_bind_api(param).then((res) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
    } else {
      message.error(res.data.msg)
    }
    initDataPurchaseList(id.value)
    initadataNeedPurchaseList()
  })
  emit('refresh')
}

const [SplitListModel, SplitListApi] = useVbenModal({
  connectedComponent: SplitList,
})

// 打开备料拆单的弹框
function openSplit(data: any) {
  SplitListApi.setData({ data }).open()
}
function splitRefresh() {
  emit('refresh')
  initDataPurchaseList(id.value)
  initadataNeedPurchaseList()
}

function notsplit(data: any) {
  notsplitOrder({ purchase_id: data }).then((res: any) => {
    if (res.data.code === 1) {
      emit('refresh')
      initDataPurchaseList(id.value)
      initadataNeedPurchaseList()
      message.success(res.data.msg)
    } else {
      message.error(res.data.msg)
    }
  })
}
</script>

<template>
  <Modal title="查看已绑定的下单明细">
    <Page>
      <SplitListModel @refresh="splitRefresh" />
      <Table class="w-fill" bordered :data-source="PurchaseList" :columns="columns" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'res'">{{ record.material_name }}-{{ record.color_name }}-{{ record.SupplyNa }}</template>
          <template v-if="column.dataIndex === 'action'">
            <div class="flex justify-between">
              <Button type="primary" @click="openSplit(record)" size="small">备料拆单</Button>
              <Button type="primary" danger @click="delBut(record)" size="small">解除绑定</Button>
            </div>
          </template>
        </template>
      </Table>

      <Form :label-col="{ span: 7.5 }" :model="formModel" style="margin-top: 20px">
        <Row style="width: 100%">
          <Col :span="6">
            <FormItem name="reqCode" label="关键词">
              <Input v-model:value="formModel.search_text" placeholder="请输入" />
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem name="reqCode" label="采购员">
              <Select
                v-model:value="formModel.purchase_user"
                show-search
                allow-clear
                style="width: 100%; height: 100%"
                placeholder="请输入"
                :filter-option="false"
                :options="Options"
                :loading="loading"
                @search="handleSupplySearch"
                @dropdown-visible-change="handleSupplyDropdown"
              />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="查看类似料（注意颜色）">
              <Switch v-model:checked="formModel.is_material" placeholder="请输入" />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="显示被绑定">
              <Switch v-model:checked="formModel.show_bind" placeholder="请输入" />
            </FormItem>
          </Col>
          <Col :span="2">
            <Button type="primary" @click="initadataNeedPurchaseList()">检索</Button>
          </Col>
        </Row>
      </Form>
      <Table class="w-fill" bordered :data-source="NeedPurchaseList" :columns="columns1" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'scope'">{{ record.material_name }}-{{ record.color_name }}</template>
          <template v-if="column.dataIndex === 'action'">
            <div class="flex justify-between">
              <template v-if="record.sp_purchase_detail_id > 0 && record.stock_num == record.reviced_num">
                <Popconfirm title="确定撤回选中行" ok-text="确认" cancel-text="取消" @confirm="notsplit(record.purchase_id)">
                  <Button type="primary" danger size="small">撤回拆单</Button>
                </Popconfirm>
              </template>
              <Button type="primary" v-if="record.stock_num>0" @click="openSplit(record)" size="small">备料拆单</Button>
              <Button type="primary" v-if="record.bom_id <= 0" @click="addBut(record)" size="small">新增绑定</Button>
            </div>
          </template>
        </template>
      </Table>
    </Page>
  </Modal>
</template>

<style scoped></style>
